package com.LC.Service.Impl;

import com.LC.DAO.OrderSettingDAO;
import com.LC.Entity.OrderSetting;
import com.LC.Service.OrderSettingService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    OrderSettingDAO orderSettingDAO;

    @Override
    public void add(List<OrderSetting> orderSettings) {
        if (orderSettings != null && orderSettings.size() > 0) {
            for (OrderSetting orderSetting : orderSettings) {
                //根据日期查询其出现次数，判断数据库是否已经有数据
                int countByOrderDate = orderSettingDAO.findCountByOrderDate(orderSetting.getOrderDate());
                if (countByOrderDate == 0) {
                    orderSettingDAO.addOrderSetting(orderSetting);
                }
                if (countByOrderDate > 0) {
                    orderSettingDAO.editOrderSetting(orderSetting);
                }
            }
        } else {
            throw new RuntimeException();
        }

    }

    /**
     * 由月份查询当月数据
     *
     * @param date
     * @return
     */
    @Override
    public List<Map> getOrderSettingByMonth(String date) throws ParseException {
        System.out.println(date);
        String dateBegin = date + "-1";
        String dateEnd = date + "-31";
        List<OrderSetting> orderSettingByMonthList = orderSettingDAO.getOrderSettingByMonth(dateBegin,dateEnd);
        List<Map> list = new ArrayList<>();
        if (orderSettingByMonthList !=null && orderSettingByMonthList.size()>0) {
            for (OrderSetting orderSetting : orderSettingByMonthList) {
                Map orderSettingMap = new HashMap();
                orderSettingMap.put("date", orderSetting.getOrderDate().getDate());
                orderSettingMap.put("number", orderSetting.getNumber());
                orderSettingMap.put("reservations", orderSetting.getReservations());
                list.add(orderSettingMap);
            }
        }else {
            throw new RuntimeException();
        }
        return list;
    }

    /**
     * 由设置按钮更新预约人数
     * @param orderSetting
     */
    @Override
    public void OrderSettingByButton(OrderSetting orderSetting) {
        //判断当前日期是否进行了预约操作
        int countByOrderDate = orderSettingDAO.findCountByOrderDate(orderSetting.getOrderDate());
        if (countByOrderDate == 0){
            //没有预约过，执行插入
            orderSettingDAO.addOrderSetting(orderSetting);
        }else {
            //预约过，执行修改
            orderSettingDAO.editOrderSetting(orderSetting);
        }
    }
}
